<template>
  <el-dialog
    v-model="dialogVisible"
    :title="!isEdit ? '新增租户' : '编辑租户'"
    width="40%"
    @close="dialogVisible = false"
  >
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <el-form-item label="租户名称" prop="tongueTenantId">
        <el-select
          v-model="form.tongueTenantId"
          placeholder="请选择租户名称"
          :disabled="isEdit"
          class="!w-240px"
        >
          <el-option
            v-for="item in tenantList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="舌诊额度(次数)" prop="tongueQuota">
        <el-input-number
          v-model.trim="form.tongueQuota"
          placeholder="请输入舌诊额度"
          class="!w-240px"
          :min="1"
          :max="100000"
          :controls="false"
        />
      </el-form-item>
      <el-form-item label="有效期" prop="expiredTime">
        <el-date-picker
          v-model="form.expiredTime"
          value-format="x"
          type="datetime"
          placeholder="请选择有效期"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-radio-group v-model="form.supplier">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.TONGUE_SUPPLIER)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="formLoading">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, toRefs, computed } from 'vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { TongueTenantApi } from '@/api/application/tongue/leaseholder'
import { getTenantSimpleList } from '@/api/system/tenant'
const dialogVisible = ref()
const tenantList = ref([])
const formLoading = ref(false)
const form = ref({
  id: undefined,
  tongueTenantId: undefined,
  tongueQuota: 0,
  expiredTime: undefined,
  supplier: undefined
})
const isEdit = ref(false)
const rules = ref({
  tongueTenantId: [{ required: true, message: '请选择租户', trigger: 'change' }],
  // 舌诊额度：手动输入，必须是整数，最大输入 100000
  tongueQuota: [
    {
      required: true,
      message: '请输入舌诊额度',
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('请输入舌诊额度'))
        }
        callback()
      }
    }
  ],
  expiredTime: [{ required: true, message: '请选择有效期', trigger: 'change' }]
})
const emits = defineEmits<{
  (emitStr: 'success'): void
}>()
/** 重置表单 */
const resetForm = () => {
  form.value = {
    id: undefined,
    tongueTenantId: undefined,
    tongueQuota: 0,
    usedTimes: null,
    expiredTime: undefined,
    supplier: undefined
  }
  formRef.value?.resetFields()
}
const open = async (type: string, id?: number) => {
  console.log('1')
  dialogVisible.value = true
  isEdit.value = type === 'edit'
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      form.value = await TongueTenantApi.getTenant(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })
const formRef = ref()
const handleSave = async () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const obj = {
        ...form.value,
        tenantName: tenantList.value.filter((item: any) => item.id === form.value.tongueTenantId)[0]
          ?.name
      }
      console.log('obj', obj)
      let callApi: any = null
      if (form.value.id) {
        delete obj.usedTimes
        callApi = TongueTenantApi.putTenantUpdate
      } else {
        obj.status = 1
        callApi = TongueTenantApi.setTenantUpdate
      }
      const data = await callApi(obj)
      console.log('data', data)
      if (data) {
        emits('success')
        ElMessage({
          message: !isEdit.value ? '新增成功' : '编辑成功',
          type: 'success'
        })
        dialogVisible.value = false
      }
    } else {
      return false
    }
  })
}
onMounted(() => {
  getTenantSimpleList().then((res: any) => {
    tenantList.value = res
  })
})
</script>

<style scoped lang="scss"></style>
